package atom.core2.j2ee.global.init;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import atom.core0.exception.BizSysException;
import atom.core0.global.GlobalCache;
import atom.core0.global.GlobalCacheConst;
import atom.core0.global.MyProperties;
import atom.core2.j2ee.util.ServletUtil;

public class GlobalCacheInit {
	//"GBK"
	public static void loadProperties(String cacheType,String propfile) throws BizSysException
	{
		loadProperties(cacheType,propfile,"GBK");
	}
	//"/des.key"  "/global-info.bean"
	public static void loadProperties(String cacheType,String propfile,String charsetName) throws BizSysException
	{
		//读取属性文件
		//getResourceAsStream 不能使用绝对路径
		MyProperties prop = new MyProperties();
		try
		{
			InputStream inn;
			if (ServletUtil.getServletContext()==null)
			{
				inn = Object.class.getResourceAsStream(propfile);
				//InputStreamReader isr = new InputStreamReader(inn,charsetName);
				prop.load(inn,charsetName);
				inn.close();
			}
			else
			{
				String newdeskeyfile = "/WEB-INF/classes"+propfile;
				//String newdeskeyfile = GlobalInfo.class.getClassLoader().getResource("/").getPath()+deskeyfile;
				//默认从WebAPP根目录下取资源
				inn = ServletUtil.getServletContext().getResourceAsStream(newdeskeyfile);
				//InputStreamReader isr = new InputStreamReader(inn,charsetName);
				prop.load(inn,charsetName);
				inn.close();
			}
		}
		catch(Exception e)
		{
			throw new BizSysException("加载属性文件["+propfile+"]错误");
		}
		
		//属性放到map中
		
		Map parmMap = (Map)GlobalCache.getCache(cacheType);
		if (parmMap==null)
			parmMap = new ConcurrentHashMap<String,String>();
		
		//properties 遍历propertity
		//Iterator it=prop.entrySet().iterator();
		Iterator it=prop.getMap().entrySet().iterator();
		while(it.hasNext()){
		    Map.Entry entry=(Map.Entry)it.next();
		    String key = (String)entry.getKey();
		    String value = (String)entry.getValue();
		    parmMap.put(key, value);
		}		
		
		GlobalCache.setCache(cacheType, parmMap);
		
		
		//初始话异常里面的子系统代码
		GlobalCache.setSubsystemCode(GlobalCache.getCache(GlobalCacheConst.TYPE_SYSTEM,GlobalCacheConst.SUBSYSTEM_CODE));
		GlobalCache.setSubsystemName(GlobalCache.getCache(GlobalCacheConst.TYPE_SYSTEM,GlobalCacheConst.SUBSYSTEM_NAME));
	}

}
